/* eslint-disable no-param-reassign */
<template>
  <div class="h-full">
    <n-card title="🕰️巡检录入" class="h-full shadow-sm rounded-16px">
      <n-space class="w-full">
        <n-form-item label="车间:">
          <n-select
            v-model:value="selectedArea"
            filterable
            label-field="areaname"
            value-field="areaname"
            :options="areas"
            @update:value="getMachineListByArea"
          />
        </n-form-item>
        <n-form-item label="设备:">
          <n-select
            v-model:value="selectedMachine"
            filterable
            label-field="machineName"
            value-field="machineName"
            :options="machines"
          />
        </n-form-item>
        <n-form-item label=" 设备:">
          <n-input v-model:value="selectedMachine" placeholder="扫描二维码" />
        </n-form-item>
        <n-form-item label="">
          <n-button type="primary" @click="getInspectParms">
            <template #icon><icon-mdi-map-search-outline /></template>
            查询
          </n-button>
        </n-form-item>
      </n-space>
      <n-divider />
      <div class="w-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        <n-card v-for="(item, index) in inspectForm.parms" :key="index" :title="`${item.itemName}`">
          <template #header-extra>
            <div>
              <n-tag v-if="item.pass" type="success" @click="item.pass = !item.pass">正常</n-tag>
              <n-tag v-else type="warning" @click="item.pass = !item.pass">异常</n-tag>
            </div>
          </template>

          <n-input v-model:value="item.itemValue" style="width: 200px" clearable />

          <template #footer>
            <n-upload v-model:file-list="item.fileList" max:1 :action="uoloadUrl">
              <n-button>
                <template #icon><icon-carbon:cloud-upload /></template>
                上传文件
              </n-button>
            </n-upload>
            <input type="file" accept="image/*" />
          </template>
          <template #action>
            <n-space>
              <n-tag type="error">下限：{{ item.lowLimit }}</n-tag>
              <n-tag type="error">上限：{{ item.upLimit }}</n-tag>
            </n-space>
          </template>
        </n-card>
      </div>
      <n-divider />
      <!--n-form-item label="现场照片">
        <n-upload
          multiple
          directory-dnd
          action="https://www.mocky.io/v2/5e4bafc63100007100d8b70f"
          style="margin-top: 10px"
        >
          <n-upload-dragger>
            <div style="margin-bottom: 12px">
              <icon-upload :depth="3" />
            </div>
            <n-text style="font-size: 16px"> 点击或者拖动文件到该区域来上传 </n-text>
            <n-p depth="3" style="margin: 8px 0 0 0">
              请不要上传敏感数据，比如你的银行卡号和密码，信用卡号有效期和安全码
            </n-p>
          </n-upload-dragger>
        </n-upload>
      </!--n-form-item-->
      <n-divider />
      <n-button type="primary" @click="submit">
        <template #icon><icon-carbon:cloud-auditing /></template>
        提交
      </n-button>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue';
import type { UploadFileInfo } from 'naive-ui';
import { useMessage } from 'naive-ui';
import dayjs from 'dayjs';
import {
  fetchAreaList,
  fetchMachineListByArea,
  fetchInspectionItemListByAreaAndMachine,
  fetchSubmitInspectionResult
} from '@/service';
import { useAuthStore } from '@/store';
import { baseUrl } from '@/service/request';

const auth = useAuthStore();
const message = useMessage();
const uoloadUrl = `${baseUrl}/inspection/inspectionImg`;
interface inspectionItemForm {
  itemName: string;
  itemType: string;
  itemValue: string;
  upLimit: string;
  lowLimit: string;
  pass: boolean;
  fileList: UploadFileInfo[];
}
// form
const inspectForm = reactive({
  name: '',
  parms: [] as inspectionItemForm[]
});

const areas = ref<Factory.Area[]>([]);
const selectedArea = ref(null);

const getAreaList = async () => {
  const result = await fetchAreaList();
  if (result.data) {
    areas.value = result.data;
  }
};

const machines = ref<Factory.Machine[]>([]);
const selectedMachine = ref(null);
const getMachineListByArea = async () => {
  if (selectedArea.value !== null) {
    const result = await fetchMachineListByArea(selectedArea.value);
    if (result.data) {
      machines.value = result.data;
    }
  }
};

const getInspectParms = async () => {
  if (selectedArea.value !== null && selectedMachine.value !== null) {
    const result = await fetchInspectionItemListByAreaAndMachine(selectedArea.value, selectedMachine.value);
    if (result.data) {
      const formList: inspectionItemForm[] = [];
      result.data.forEach(inspectionItem => {
        const inspection: inspectionItemForm = {
          itemName: inspectionItem.itemName,
          itemType: inspectionItem.itemType,
          upLimit: inspectionItem.upLimit,
          lowLimit: inspectionItem.lowLimit,
          itemValue: '',
          pass: true,
          fileList: []
        };
        formList.push(inspection);
      });
      inspectForm.parms = formList;
    }
  }
};

const submit = async () => {
  const inspectionResults: Factory.InspectionResult[] = [];
  if (selectedMachine.value !== null) {
    inspectForm.parms.forEach(element => {
      const filestringList: string[] = [];
      element.fileList.forEach(file => {
        const filestring = `${uoloadUrl}/${file.name}`;
        filestringList.push(filestring);
      });
      const filestring = filestringList.join(',');
      const inspectionResult: Factory.InspectionResult = {
        machineName: selectedMachine.value as unknown as string,
        itemName: element.itemName,
        eventTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        eventUser: auth.userInfo.userId,
        itemValue: element.itemValue,
        lowLimit: element.lowLimit,
        upLimit: element.upLimit,
        files: filestring,
        pass: element.pass ? '通过' : '未通过'
      };
      if (inspectionResult.itemValue !== '') inspectionResults.push(inspectionResult);
    });
    const result = await fetchSubmitInspectionResult(inspectionResults);
    if (result.data) {
      message.success('处理成功！');
    }
  }
};
onMounted(() => {
  getAreaList();
});

watch(
  inspectForm,
  () => {
    // inspectForm.parms.forEach();
  },
  {
    // 首次渲染组件就触发一次
    immediate: true
  }
);
</script>
<style scoped></style>
